#include "thread_pool.h"
#include "user_check.h"
#include "user_register.h"
#include "datebase.h"
#include <mysql/mysql.h>

#define STR_LEN 8
void GenerateStr(char* str){
    int i,flag;
    srand(time(NULL));
    for(i=0;i<STR_LEN;i++){
        flag=rand()%3;
        switch(flag)
        {
        case 0:str[i]=rand()%26+'a'; break;
        case 1:str[i]=rand()%26+'A'; break;
        case 2:str[i]=rand()%10+'0'; break;
        }
    }
    str[STR_LEN]='\0';
    printf("%s\n",str);
    
}

void Register1(user_info_t* user,MYSQL_STMT* stmt,MYSQL pconn){
    printf("Register\n");
    train_t t;
    memset(&t,0,sizeof(t));

    if(select_username(user->name,stmt,pconn)){
        char str[STR_LEN+1]={0};
        GenerateStr(str);
        char str2[13];
        sprintf(str2,"%s%s%s","$6$",str,"$");
        str2[12]='\0';
        t.len=strlen(str2);
        t.type=TASK_LOGIN_SECTION1_RESP_OK;
        strncpy(t.buff,str2,t.len);
        sendn(user->sockfd,&t,8+t.len);
    }
    else{
        t.type=TASK_REGISTER_SECTION1_RESP_ERROR;
        sendn(user->sockfd,&t,8);
    }
    return;
}

void Register2(user_info_t* user,MYSQL_STMT* stmt,MYSQL pconn){
    printf("Register2\n");
    train_t t;
    memset(&t,0,sizeof(t));

    if(insert_username(user,stmt,pconn)){
        printf("注册成功！\n");
        user->status=STATUS_LOGIN;
        t.type=TASK_REGISTER_SECTION2_RESP_OK;
        user->pwd=0;
        user->user_id=select_userid(user->name,stmt,pconn);
        insert_filetable(user->pwd,user->name,user->user_id,stmt,pconn);
        user->pwd= select_rootpwd(user->user_id,stmt,pconn);
        update_pwd(user->user_id,user->pwd,stmt,pconn);
        
        sendn(user->sockfd,&t,8);
    }else{
        printf("注册失败！\n");
        t.type=TASK_REGISTER_SECTION2_RESP_ERROR;
        sendn(user->sockfd,&t,8);
    }
    return;

}

